//
//  DeveloperViewController.swift
//  CodeLibrary_Swift
//
//  Created by 陆文宇 on 2017/5/25.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import UIKit
import Alamofire
import Kingfisher

let richCellIdentifier = "richCell"

class WordImageViewController: YYController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, RichTypeTableViewCellEditing {
    
    @IBOutlet weak var tableView: UITableView!
    var dataSource: [RichModel] = []
    var filetag = ""
    var content = ""
    var doneClosure: ((String) -> Void)?
    
    var uploadCount = 0
    
    var editingStyle = UITableViewCellEditingStyle.delete
    var addIndex = 0
    
    override func yy_configNaviItem(_ naviItem: UINavigationItem) {
        super.yy_configNaviItem(naviItem)
        
        let doneItem = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(done(_:)))
        let previewItem = UIBarButtonItem(title: "预览", style: .plain, target: self, action: #selector(preview))
        navigationItem.rightBarButtonItems = [doneItem, previewItem]
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if !yy_isViewAppear {
            analysisJsonString(content)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        automaticallyAdjustsScrollViewInsets = false
        tableView.register(UINib(nibName: "RichTypeTableViewCell", bundle: nil), forCellReuseIdentifier: richCellIdentifier)
    }
    
    func analysisJsonString(_ json: String?) {
        if let json = json {
            if let jsonArr = try? JSONSerialization.jsonObject(with: json.data(using: .utf8)!, options: []) as! [[String: Any]] {
                if jsonArr.isEmpty {
                    return
                }
                
                var count = 0
                yy_showStatusHUD(status: "正在加载(\(count)/\(jsonArr.count))")
                for json in jsonArr {
                    let rich = RichModel()
                    rich.richType = RichType(rawValue: json["type"] as! Int)
                    let value = json["value"] as! String
                    if rich.richType.rawValue == 2 {
                        rich.imageUrl = value
                        KingfisherManager.shared.retrieveImage(with: URL(string: value)!, options: nil, progressBlock: nil, completionHandler: { [weak self] (image, error, _, _) in
                            if error == nil {
                                rich.image = image
                            }
                            
                            count += 1
                            self?.yy_showStatusHUD(status: "正在加载(\(count)/\(jsonArr.count))")
                            if count == jsonArr.count {
                                self?.yy_dismissHUD()
                                self?.tableView.reloadData()
                            }
                        })
                    } else if rich.richType.rawValue == 1 {
                        rich.txt = value
                        count += 1
                        yy_showStatusHUD(status: "正在加载(\(count)/\(jsonArr.count))")
                        if count == jsonArr.count {
                            yy_dismissHUD()
                            self.tableView.reloadData()
                        }
                    }
                    self.dataSource.append(rich)
                    if count == jsonArr.count {
                        yy_dismissHUD()
                        self.tableView.reloadData()
                    }
                }
            } else {
                yy_dismissHUD()
            }
        } else {
            yy_dismissHUD()
        }
    }
    
    @objc func preview() {
        let preview = PreviewViewController(nibName: "PreviewViewController", bundle: nil)
        preview.dataSource = dataSource
        let navi = UINavigationController(rootViewController: preview)
        self.present(navi, animated: true, completion: nil)
    }
    
    @objc func done(_ sender: UIBarButtonItem) {
        sender.isEnabled = false
        uploadCount = 0
        
        var jsonArr = [[String: Any]]()
        yy_showStatusHUD(status: "正在上传(\(self.uploadCount)/\(self.dataSource.count))")
        YYQiniu.getToken { (token) in
            for content in self.dataSource {
                if content.richType == .txt {
                    jsonArr.append(["type": 1, "value": content.txt!])
                    self.uploadCount += 1
                    self.yy_showStatusHUD(status: "正在上传(\(self.uploadCount)/\(self.dataSource.count))")
                } else if content.richType == .image {
                    if content.imageUrl == nil {
                        let filename = self.filetag + "/" + UIImage.yy_createName()
                        let imageUrl = imageUrlPrex + "/" + filename
                        content.imageUrl = imageUrl
                        jsonArr.append(["type": 2, "value": imageUrl])
                        
                        YYQiniu.upload(content.image!.yy_JPEGData(), key: filename, token: token, success: { (filename) in
                            yy_Log("filename: \(filename)")
                            self.uploadCount += 1
                            self.yy_showStatusHUD(status: "正在上传(\(self.uploadCount)/\(self.dataSource.count))")
                            if self.uploadCount == self.dataSource.count {
                                self.yy_dismissHUD()
                                self.commit()
                                sender.isEnabled = true
                            }
                        }, failure: {
                            self.yy_showErrorHUD(status: "上传失败")
                        })
                    } else {
                        self.uploadCount += 1
                        self.yy_showStatusHUD(status: "正在上传(\(self.uploadCount)/\(self.dataSource.count))")
                        jsonArr.append(["type": 2, "value": content.imageUrl!])
                    }
                }
            }
            
            if JSONSerialization.isValidJSONObject(jsonArr) {
                let jsonData = try! JSONSerialization.data(withJSONObject: jsonArr, options: [])
                self.content = String(data: jsonData, encoding: .utf8)!
            }
            
            if self.uploadCount == self.dataSource.count {
                self.yy_dismissHUD()
                self.commit()
                sender.isEnabled = true
            }
        }
        
    }
    
    func commit() {
        doneClosure?(content)
        cancel()
    }
    
    @IBAction func add(_ sender: Any) {
        if sender is UIButton {
            addIndex = dataSource.count
        }
        
        let addView = YYActionSheetView(title: "选择添加内容")
        addView.addAction(YYActionSheetAction(title: "文字", image: #imageLiteral(resourceName: "word"), action: {
            let wordVC = YYTextController(nibName: "YYTextController", bundle: nil)
            wordVC.placeholder = "请填写文字描述"
            wordVC.canEmpty = false
            wordVC.textCountLimit = 200
            wordVC.doneTitle = "确认"
            wordVC.saveClosure = { [unowned self] (word) in
                let rich = RichModel()
                rich.richType = .txt
                rich.txt = word
                self.dataSource.insert(rich, at: self.addIndex)
                self.tableView.insertRows(at: [IndexPath(row: self.addIndex, section: 0)], with: .automatic)
                self.tableView.scrollToRow(at: IndexPath(row: self.addIndex, section: 0), at: .bottom, animated: true)
            }
            self.yy_push(vc: wordVC)
        }))
        addView.addAction(YYActionSheetAction(title: "拍照", image: #imageLiteral(resourceName: "photo"), action: {
            let image = UIImagePickerController()
            if !UIImagePickerController.isSourceTypeAvailable(.camera) {
                self.yy_showErrorHUD(status: "相机不支持")
                return
            }
            image.sourceType = .camera
            image.allowsEditing = false
            image.delegate = self
            self.present(image, animated: true, completion: nil)
        }))
        addView.addAction(YYActionSheetAction(title: "图片", image: #imageLiteral(resourceName: "image"), action: {
            let image = UIImagePickerController()
            image.allowsEditing = false
            image.delegate = self
            self.present(image, animated: true, completion: nil)
        }))
        addView.show()
    }
    
    @objc func cancel() {
        yy_pop()
    }
    
    override func setEditing(_ editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)
        
        editingStyle = editing ? .insert : .delete
        tableView.setEditing(editing, animated: animated)
    }
    
    // MARK: -TableViewDelegate
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: richCellIdentifier, for: indexPath) as! RichTypeTableViewCell
        cell.controller = self
        let content = dataSource[indexPath.row]
        if content.richType == .txt {
            cell.richType = .txt
            cell.richLabel?.text = content.txt
        } else {
            cell.richType = .image
            if let image = content.image {
                cell.richImageView.image = image
            } else {
                cell.richImageView.kf.setImage(with: URL(string: content.imageUrl!)!, placeholder: UIImage(named: "placeImage3-2"), completionHandler: { (image, error, _, _) in
                    if error == nil {
                        if content.image == nil {
                            content.image = image
                            if tableView.indexPathsForVisibleRows?.contains(indexPath) ?? false {
                                //                                tableView.reloadRows(at: [indexPath], with: .none)
                                tableView.reloadData()
                            }
                        }
                    }
                })
            }
        }
        
        if indexPath.row == 0 {
            cell.upView.isHidden = true
            cell.stackViewHeight.constant = 100
        } else {
            cell.upView.isHidden = false
            cell.stackViewHeight.constant = 150
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let content = dataSource[indexPath.row]
        if content.richType == .txt {
            let wordHeight = (content.txt! as NSString).boundingRect(with: CGSize(width: screenWidth - 20, height: CGFloat.infinity), options: [.usesLineFragmentOrigin], attributes: [NSAttributedStringKey.font: mainFont], context: nil).size.height + 40
            if wordHeight < 150 - 10 {
                return 150
            } else {
                return wordHeight + 10
            }
        } else {
            if let image = content.image {
                return (screenWidth - 20) / image.size.width * image.size.height + 10
            } else {
                return (screenWidth - 20) / 3 * 2 + 10
            }
        }
    }
    
    func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
        if (tableView.cellForRow(at: indexPath) as! RichTypeTableViewCell).richType == .image {
            return true
        }
        return true
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let cell = tableView.cellForRow(at: indexPath) as! RichTypeTableViewCell
        if cell.richType == .txt {
            let wordVC = YYTextController(nibName: "YYTextController", bundle: nil)
            wordVC.text = cell.richLabel.text!
            wordVC.canEmpty = false
            wordVC.textCountLimit = 200
            wordVC.doneTitle = "确认"
            wordVC.saveClosure = { [unowned self] (word) in
                let rich = RichModel()
                rich.richType = .txt
                rich.txt = word
                self.dataSource.replaceSubrange(indexPath.row ..< indexPath.row + 1, with: [rich])
                tableView.reloadRows(at: [indexPath], with: .automatic)
            }
            navigationController?.pushViewController(wordVC, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return editingStyle
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            dataSource.remove(at: indexPath.row)
            tableView.reloadData()
        } else {
            addIndex = indexPath.row + 1
            add(tableView)
        }
    }
    
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        guard sourceIndexPath.row != destinationIndexPath.row else {
            return
        }
        
        let source = dataSource.remove(at:sourceIndexPath.row)
        dataSource.insert(source, at: destinationIndexPath.row)
    }
    
    func richCell(cell: RichTypeTableViewCell, style: RichTypeTableViewCell.EditingStyle) {
        let indexPath = tableView.indexPath(for: cell)!
        switch style {
        case .add:
            addIndex = indexPath.row + 1
            add(cell)
        case .move:
            let source = dataSource.remove(at:indexPath.row)
            dataSource.insert(source, at: indexPath.row - 1)
            tableView.reloadData()
        case .delete:
            dataSource.remove(at: indexPath.row)
            tableView.reloadData()
        }
    }
    
    // MARK: -UIImagePickerControllerDelegate
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let type: String = (info[UIImagePickerControllerMediaType] as! String)
        //当选择的类型是图片
        if type == "public.image" {
            let image = info[UIImagePickerControllerOriginalImage] as! UIImage
            
            let rich = RichModel()
            rich.richType = .image
            rich.image = image
            self.dataSource.insert(rich, at: self.addIndex)
            self.tableView.insertRows(at: [IndexPath(row: self.addIndex, section: 0)], with: .automatic)
            self.tableView.scrollToRow(at: IndexPath(row: self.addIndex, section: 0), at: .bottom, animated: true)
            
        }
        picker.dismiss(animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

